import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import '../service/database_service.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class TodoItem {
  String id;          
  String title;       
  bool isCompleted;   
  DateTime? reminderTime;

  TodoItem({
    required this.id,
    required this.title,
    this.isCompleted = false,
    this.reminderTime,
  });

  TodoItem copyWith({
    String? id,
    String? title,
    bool? isCompleted,
    DateTime? reminderTime,
  }) {
    return TodoItem(
      id: id ?? this.id,
      title: title ?? this.title,
      isCompleted: isCompleted ?? this.isCompleted,
      reminderTime: reminderTime ?? this.reminderTime,
    );
  }
}

class TodoPage extends StatefulWidget {
  const TodoPage({super.key});

  @override
  State<TodoPage> createState() => _TodoPageState();
}

class _TodoPageState extends State<TodoPage> {
  final List<TodoItem> _todos = [];  
  final DatabaseService _db = DatabaseService();  
  bool _isLoading = true;
  final notification = FlutterLocalNotificationsPlugin();
  
  final List<Color> _cardColors = [
    Colors.green.shade100, 
    Colors.blue.shade100, 
    Colors.yellow.shade100, 
  ];
  
  @override
  void initState() {
    super.initState();
    _configureLocalTimeZone();
    _initializeNotifications();
    _loadTodos();  
  }

  Future<void> _configureLocalTimeZone() async {
  tz.initializeTimeZones();
  final timeZone = await FlutterTimezone.getLocalTimezone();
  tz.setLocalLocation(tz.getLocation(timeZone));
  }
  
  Future<void> _initializeNotifications() async {
    const initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/launcher_icon');

    await Permission.notification.request();
    await Permission.scheduleExactAlarm.request();

    const  initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
    );

    await notification.initialize(initializationSettings);

    const channel = AndroidNotificationChannel(
      'todo_reminders',
      '待办提醒',
      importance: Importance.max,
    );

    await notification.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel);
  }

  Future<void> _scheduleNotification(TodoItem todo) async {
    if (todo.reminderTime == null || todo.isCompleted) return; 

    final now = tz.TZDateTime.now(tz.local).toUtc();
    final scheduleDate = tz.TZDateTime.from(todo.reminderTime!, tz.local).toUtc();

    if (scheduleDate.isBefore(now)) {
      return;
    }

    const androidNotification = AndroidNotificationDetails(
      'todo_reminders',
      '待办提醒', 
      importance: Importance.max,
      priority: Priority.high,
      visibility: NotificationVisibility.public,
    );

    const notificationDetail = NotificationDetails(android: androidNotification);
    
    await notification.zonedSchedule(
      todo.id.hashCode, 
      '待办提醒', 
      todo.title, 
      scheduleDate, 
      notificationDetail,
      androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
    );

    await notification.show(
      0,
      '提示',
      '成功设置定时通知',
      notificationDetail,
    );
  }

  Future<void> _cancelNotification(String id) async {
     await notification.cancel(id.hashCode); 
  }

  Future<void> _loadTodos() async {
    try {
      final todos = await _db.getAllTodos();
      setState(() {
        _todos.clear();
        for (var todo in todos) {
          _todos.add(TodoItem(
            id: todo['id'],
            title: todo['title'],
            isCompleted: todo['is_completed'] == 1,
            reminderTime: todo['reminder_time'] != null ? DateTime.parse(todo['reminder_time']) : null,
          ));
        }
        _todos.sort((a, b) => a.isCompleted ? 1 : -1);
        _isLoading = false;
      });
      for (var todo in _todos) {
        await _scheduleNotification(todo);
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }  
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(  
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Icon(Icons.check_circle,size: 30),
            const SizedBox(width: 8,),
            Column(
              children: [
                const Text('待办',style: TextStyle(fontWeight: FontWeight.bold),), 
                Text(
                  '${_todos.length}条待办', 
                  style: TextStyle(fontSize: 12, color: Colors.grey.shade700),
                ),
              ]
            ),
          ],
        ),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _todos.isEmpty 
              ? const Center(child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.check_circle_outline, color: Colors.grey, size: 80),
                  SizedBox(height: 16,),
                  Text('无待办', style: TextStyle(color: Colors.grey, fontSize: 20),),
                ],
              ))
              : ListView.builder(
                itemCount: _todos.length,
                itemBuilder: (context, index) {
                  final todo = _todos[index];
                  return Slidable(
                    endActionPane: ActionPane(
                      motion: const ScrollMotion(), 
                      extentRatio: 0.2,
                      children: [
                        Container(
                          margin: const EdgeInsets.all(2.0),
                          padding: const EdgeInsets.all(2.0),
                          decoration: BoxDecoration(
                            color: Colors.grey.shade400, 
                            shape: BoxShape.circle, 
                          ),
                          child: IconButton(
                            icon: const Icon(Icons.delete, color: Colors.black,),
                            onPressed:() async {
                              final result = await _showDeleteDialog(todo);
                              if (result) {
                                try {
                                  await _db.deleteTodo(todo.id);
                                  _cancelNotification(todo.id);
                                  _loadTodos();
                                } catch (e) {
                                  if (mounted) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(content: Text('删除待办失败: $e')),
                                    );
                                  }
                                }
                              }
                            }, 
                          ),
                        ),
                      ],
                    ),
                    child: Card(
                      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      color: todo.isCompleted ? Colors.grey.shade300 : _cardColors[index % 3],
                      child: ListTile(
                        contentPadding: const EdgeInsets.only(left: 4, right: 16),
                        horizontalTitleGap: 4,
                        leading: IconButton(
                          icon: Icon(
                            todo.isCompleted ? Icons.check_circle : Icons.circle_outlined, 
                            color: todo.isCompleted ? Colors.grey : Colors.black, 
                          ),
                          onPressed: () async {
                            await _db.updateTodoStatus(todo.id, !todo.isCompleted);
                            setState(() {
                              todo.isCompleted = !todo.isCompleted;
                              _todos.sort((a, b) => a.isCompleted ? 1 : -1);
                            });
                            if (todo.isCompleted) {
                              _cancelNotification(todo.id);
                            } else {
                              await _scheduleNotification(todo);
                            }
                          },
                        ),
                        title: Text(
                          todo.title,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            decoration: todo.isCompleted ? TextDecoration.lineThrough : null, 
                            color: todo.isCompleted ? Colors.grey : Colors.black, 
                          ),
                        ),
                        subtitle: todo.reminderTime != null
                          ? Text('${todo.reminderTime?.month}月${todo.reminderTime?.day}日 ${todo.reminderTime?.hour}:${todo.reminderTime?.minute.toString().padLeft(2, '0')}')
                          : null,
                        onTap: () {
                          _editTodo(todo);
                        },
                      ),
                    ),
                  );
                }
              ),  
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _addTodo();
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  Future<void> _addTodo() async{
    final titleController = TextEditingController();
    DateTime? selectedTime;

    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加待办'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(  
              controller: titleController,
              maxLength: 99,
              maxLines: null,
              decoration: const InputDecoration(
                hintText: '请输入待办事项',
                counterText: '',
              ),
            ),
            StatefulBuilder( 
              builder: (context, setState) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextButton.icon(
                      icon: const Icon(Icons.alarm),
                      label: Text(
                        selectedTime == null
                            ? '设置提醒时间'
                            : '${selectedTime!.toString().split(' ')[0]}  ${selectedTime!.hour}:${selectedTime!.minute.toString().padLeft(2, '0')}'
                      ),
                      onPressed: () async {
                        final pickedDate = await showDatePicker(
                          context: context,
                          initialDate: selectedTime ?? DateTime.now(),
                          firstDate: DateTime.now().subtract(const Duration(days: 0)),
                          lastDate: DateTime.now().add(const Duration(days: 365)),
                        );
                        if (pickedDate != null) {
                          final pickedTime = await showTimePicker(
                            context: context,
                            initialTime: TimeOfDay.fromDateTime(selectedTime ?? DateTime.now()),
                          );
                          if (pickedTime != null) {
                            setState(() { 
                              selectedTime = DateTime(
                                pickedDate.year,
                                pickedDate.month,
                                pickedDate.day,
                                pickedTime.hour,
                                pickedTime.minute,
                              );
                            });
                          }
                        }
                      },
                    ),
                    if (selectedTime != null)
                    TextButton.icon(
                      icon: const Icon(Icons.clear),
                      label: const Text('清除提醒'),
                      onPressed: () {
                        setState(() {
                          selectedTime = null;
                        });
                      },
                    ),
                  ],
                );
              },
            ),
          ],
        ),
        actions: [
          TextButton(  
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(  
            onPressed: () async {
              if (titleController.text.isNotEmpty) {
                final id = const Uuid().v4();
                await _db.insertTodo(id, titleController.text, reminderTime: selectedTime);
                final todo = TodoItem(
                    id: id,
                    title: titleController.text,
                    isCompleted: false,
                    reminderTime: selectedTime,
                  );
                setState(() {_todos.insert(0, todo);
                });
                if (selectedTime != null) {
                  _scheduleNotification(todo);
                }
                Navigator.pop(context);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('待办事项不能为空'))
                );
              }
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  Future<void> _editTodo(TodoItem todo) async {
    final titleController = TextEditingController(text: todo.title);
    DateTime? selectedTime = todo.reminderTime;

    await showDialog(
      context: context, 
      builder: (context) => AlertDialog(
        title: const Text('编辑待办'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: titleController,
              maxLength: 99,
              maxLines: null,
              decoration: const InputDecoration(
                hintText: '请输入待办事项',
                counterText: '',
              ),
            ),
            StatefulBuilder( 
              builder: (context, setState) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TextButton.icon(
                      icon: const Icon(Icons.alarm),
                      label: Text(
                        selectedTime == null
                            ? '设置提醒时间'
                            : '${selectedTime!.toString().split(' ')[0]}  ${selectedTime!.hour}:${selectedTime!.minute.toString().padLeft(2, '0')}' 
                      ),
                      onPressed: () async {
                        final pickedDate = await showDatePicker(
                          context: context,
                          initialDate: selectedTime ?? DateTime.now(),
                          firstDate: DateTime.now().subtract(const Duration(days: 0)),
                          lastDate: DateTime.now().add(const Duration(days: 365)),
                        );
                        if (pickedDate != null) {
                          final pickedTime = await showTimePicker(
                            context: context,
                            initialTime: TimeOfDay.fromDateTime(selectedTime ?? DateTime.now()),
                          );
                          if (pickedTime != null) {
                            setState(() { 
                              selectedTime = DateTime(
                                pickedDate.year,
                                pickedDate.month,
                                pickedDate.day,
                                pickedTime.hour,
                                pickedTime.minute,
                              );
                            });
                          }
                        }
                      },
                    ),
                    if (selectedTime != null) 
                    TextButton.icon(
                      icon: const Icon(Icons.clear),
                      label: const Text('清除提醒'),
                      onPressed: () {
                        setState(() {
                          selectedTime = null;
                        });
                      },
                    ),
                  ],
                );
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              if (titleController.text.isNotEmpty) {
                Navigator.pop(context);
                try {
                  final updatedTodo = todo.copyWith(title: titleController.text, reminderTime: selectedTime);
                  await _db.updateTodo(todo.id, titleController.text, reminderTime: selectedTime);
                  setState(() {_todos[_todos.indexOf(todo)] = updatedTodo;});
                  if (selectedTime != null) {
                  _scheduleNotification(updatedTodo);
                } else {
                  _cancelNotification(todo.id);
                }
                } catch (e) {
                 if (mounted) {
                   ScaffoldMessenger.of(context).showSnackBar(
                     SnackBar(content: Text('更新待办失败: $e')),
                   );
                 }
                }
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('待办事项不能为空'))
                );
              }
            }, 
            child: const Text('确定'),
          ),
        ]
      )
    ); 
  }

  Future<bool> _showDeleteDialog(TodoItem todo) async {
    final result = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除待办'),
        content: const Text('确定删除此待办吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除'),
          ),
        ],
      ),
    );
    return result ?? false;
  }
}


